<?php
/**
 * Class C_Order 客户端订单资源
 */
namespace V7;

class  C_Order extends \V6\C_Order
{
    function __construct()
    {
        require_once(ROOT . 'lib/AliPay/AliPayConfig.php');
        require_once(ROOT . 'lib/WxPay/WxPay.php');
    }
    public function post(array $req, array $post, &$result)
    {
        try {
            /* 授权验证【开始】 */
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('payload', $post)) {
                return 'require payload';
            }

            $data = base64_decode($post['payload']);
            @parse_str($data, $data);
            $orderList = substr($data['orderList'], 0, strlen($data['orderList']));
            $orderDetailsArray = self::order_product_array($orderList);
            if ($orderDetailsArray == false ) {
                return '至少选着一个商品！！！';
            }
            /*if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $orderDetailsArray[0]['enterprise_id'], $req['t'] . $post['payload'], $req['k']) == false) {
                return 'data illegal';
            }*/

            //解析payload
            $detail_list = array();
            foreach ($orderDetailsArray as $k => $v) {
                $order_detail_cls = new \Cls\Order\Detail();
                $order_detail_cls->create($v['product_id'], $v['sku_id'], $v['product_num']);
                $detail_list[] = $order_detail_cls;

            }
            $customer_hand = new \Biz\EnterpriseCustomerHandler();
            $customer_cls = $customer_hand::getEnterpriseCustomerById($orderDetailsArray[0]['enterprise_id'], $req['uid']);

            // 操作库存前判断企业是否开启仓库审核
            if (\Biz\Workflow\RelevanceGlobalConfig::isEnterpriseCheckStock($orderDetailsArray[0]['enterprise_id'])) {
                // 判断超售库存
                foreach ($detail_list as $order_cls) {
                    //获取产品详情
                    $product_biz = new \Biz\Product\Product();
                    $product_cls = $product_biz->getProductListById($order_cls->getProductId());
                    foreach ($product_cls->getSkuList() as $k => $skuinfo) {
                        if ($skuinfo->getId() == $order_cls->getProductSkuId()) {
                            $attr = $this->unsertlizeAttr($skuinfo->getAttr());
                        }
                    }
                    //获取产品sku的可用库存
                    $stock_handler = new \Biz\StockHandler();
                    $stock_cls = $stock_handler->loadBySkuIdAndProductId($customer_cls->getWarehouseId(),$order_cls->getProductSkuId(), $order_cls->getProductId());
                    //如果库存表中不存在该条数据，新增一条
                    if (!$stock_cls) {
                        $stock = new \Cls\Warehouse\Stock();
                        $stock->setEnterpriseId($product_cls->getEnterpriseId());
                        $stock->setWarehouseId($customer_cls->getWarehouseId()); //仓库 对应没有sku记录的仓库
                        $stock->setSkuId($order_cls->getProductSkuId());
                        $stock->setProductId($order_cls->getProductId());
                        $stock->setProductName($product_cls->getName());
                        $stock->setProductAttr($attr);
                        $stock->getInsertTime(date('Y-m-d H:i:s', time()));
                        $stock_handler->insert($stock);
                        $stock_cls = $stock_handler->loadBySkuIdAndProductId($customer_cls->getWarehouseId(),$order_cls->getProductSkuId(), $order_cls->getProductId());
                    }

                    //不允许超售的判断库存 && 下单数量大于可用库存
                    if ($product_cls->getOverSale() == 1 && $order_cls->getAmount() > $stock_cls->getAvailableStock()) {
                        return $stock_cls->getProductName() . '属性为' . $stock_cls->getProductAttr() . '的产品库存不足！';
                    }
                }
            }

            //创建订单
            $order_cls = new \Cls\Order\Order();
            $order_cls->create($orderDetailsArray[0]['enterprise_id'], $req['uid'], $orderDetailsArray[0]['channel_id'], $detail_list);

            $order_handler = new \Biz\OrderHandler();
            $order_cls = $order_handler->insert($order_cls);
            if(!is_object($order_cls)){
                return '订单总额不能小于￥'.$order_cls;
            }
            //拼订单数据
            if ($order_cls instanceof \Cls\Order\Order) {
                //订单SKU详情
                $tmp = $this->pieceOrder($order_cls);
                //时间选择列表
                $channel_biz = new \Biz\ChannelHandler();
                $channel_cls = $channel_biz->getDeliveryByChannelIdAndOrderId($order_cls->getEnterpriseChannelId(),$order_cls->getInsertTime());
                $tmp['dataList'] = $channel_cls;
                //用户信息
                $tmp['userInfo'] = $this->pieceUserInfo($order_cls);
                // 添加支付方式信息
                $pay_type_list = array(
                    array(
                        'type' => '1',
                        'name' => '线上支付',
                        'is_checked' => 1,
                        'items' => array()
                    ),
                    array(
                        'type' => '0',
                        'name' => '线下支付',
                        'is_checked' => 0,
                        'items' => array()
                    )
                );

                $pay_handler = new \Biz\PayHandler();
                $channel_handler = new \Biz\ChannelHandler();
                $channel_cls = $channel_handler::getChannelById($orderDetailsArray[0]['channel_id']);
                $channel_pay = $channel_cls->getChannelPayInfo();
                if($channel_pay){
                    foreach ($channel_pay as $key=>$channel_pay_cls){
                        if($channel_pay_cls->getPayType() == \Cls\Channel\ChannelPay::pay_online_type){
                            $pay_id = $channel_pay_cls->getPayId();
                            $online_pay_list[] = $pay_handler->getByOnlineId($pay_id);
                        }else{
                            $pay_id = $channel_pay_cls->getPayId();
                            $offline_pay_list[] = $pay_handler->getByOfflineId($pay_id);
                        }
                    }
                }
                $online_pay_list = isset($online_pay_list) ? $online_pay_list : array();
                $offline_pay_list = isset($offline_pay_list) ? $offline_pay_list : array();
                foreach ($pay_type_list as $key => $value) {
                    if ($value['type'] == '1') {
                        $pay_type_list[$key]['items'] = $this->pieceOnline($online_pay_list);
                    } else if ($value['type'] == '0') {
                        $pay_type_list[$key]['items'] = $this->pieceOffline($offline_pay_list);
                    }
                }
                $tmp['payTypeList'] = $pay_type_list;

                //增加订单至 solr_order
                $createSolrOrder = $this->createSolrOrderRow($tmp);
                if ($createSolrOrder) {
                    $result = $tmp;
                    return '';
                } else {
                    return 'create solr order error';
                }
            }
            return 'create order filed';

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * orderList = productId;num;cid; eid;skuId,productId;num;cid;eid;skuId
     * 订单参数列    产品id    数量 渠道id 企业ID skuid ,产品id   数量 渠道id 企业id skuid
     * @param $string
     * @return array
     */
    private static function order_product_array($string)
    {
        if (empty($string)) return false;
        $toListArray = explode(',', $string);
        $tmpOrderProductArray = array();
        foreach ($toListArray as $k => $v) {
            $tmp = array();
            $productList = explode(';', $v);
            $tmp['product_id'] = $productList[0];
            $tmp['product_num'] = $productList[1];
            $tmp['channel_id'] = $productList[2];
            $tmp['enterprise_id'] = $productList[3];
            $tmp['sku_id'] = $productList[4];
            $tmpOrderProductArray[] = $tmp;
        }
        if ($tmpOrderProductArray) return $tmpOrderProductArray;
        return false;
    }

    /*
     * 拼凑订单头
     * @param  Cls\Order\Order  $order_cls
     */
    private function pieceOrder(\Cls\Order\Order $order_cls)
    {
        $orderHeader = array();
        $orderBody = array();
        if($order_cls->getIsPayType()==\Cls\Order\Order::IS_PAY_TYPE_OFFLINE){
            $pay_type = '线下支付';
        }else{
            $pay_type = '线上支付';
        }
        $orderHeader['id'] = $order_cls->getId();
        $orderHeader['ordercode'] = $order_cls->getCode();
        $orderHeader['enterprise_id'] = (string)$order_cls->getEnterpriseId();
        $orderHeader['enterprise_customer_id'] = (string)$order_cls->getEnterpriseCustomerId();
        $orderHeader['enterprise_channel_id'] = (string)$order_cls->getEnterpriseChannelId();
        $orderHeader['status'] = (string)$order_cls->getStatus();
        $orderHeader['contact'] = (string)$order_cls->getContact();
        $orderHeader['tel'] = (string)$order_cls->getTelephone();
        $orderHeader['price'] = (string)$order_cls->getPrice();
        $orderHeader['discount'] = (string)$order_cls->getDiscount();
        $orderHeader['coupon'] = (string)$order_cls->getConupon();
        $orderHeader['need_pay_price'] = (string)$order_cls->getNeedPayPrice();
        $orderHeader['pay_status'] = (string)$order_cls->getPayStatus();
        $orderHeader['pay_datetime'] = (string)$order_cls->getPayTime();
        $orderHeader['pay_message'] = (string)$order_cls->getPayMessage();
        $orderHeader['delivery_status'] = (string)$order_cls->getDeliveryStatus();
        $orderHeader['delivery_charge'] = (string)$order_cls->getDeliveryCharge();
        $orderHeader['delivery_time'] = (string)$order_cls->getDeliveryTime();
        $orderHeader['delivery_province_id'] = (string)$order_cls->getDeliveryProvinceId();
        $orderHeader['delivery_city_id'] = (string)$order_cls->getDeliveryCityId();
        $orderHeader['delivery_address'] = (string)$order_cls->getDeliveryAddress();
        $orderHeader['remark'] = (string)$order_cls->getRemark();
        $orderHeader['active_discount'] = (string)$order_cls->getActiveDiscount();
        $orderHeader['insert_time'] = (string)$order_cls->getInsertTime();
        $orderHeader['update_time'] = (string)$order_cls->getUpdateTime();
        $orderHeader['is_pay_type'] = (string)$order_cls->getIsPayType();
        $orderHeader['pay_type_item_id'] = $order_cls->getPayTypeItemId() ? (string)$order_cls->getPayTypeItemId() : '';
        $orderHeader['transaction_id'] = (string)$order_cls->getTransactionId();
        $orderHeader['is_del'] = '0';
        $orderHeader['pay_class_type'] = $pay_type ? (string)$pay_type : '';
        $orderSettlement = array(array('name'=>'商品金额','value'=>(string)$order_cls->getPrice()),array('name'=>'商品折扣','value'=>(string)$order_cls->getDiscount()),array('name'=>'商品运费','value'=>(string)$order_cls->getDeliveryCharge()),array('name'=>'商品优惠','value'=>(string)$order_cls->getConupon()));
        $skuList = $order_cls->getDetailList();
        if ($skuList) {
            foreach ($skuList as $k => $sku_cls) {
                if (is_object($sku_cls)) {
                    $inco_url = $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() ? $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() : '';
                    $temp = array();
                    $temp['id'] = (string)$sku_cls->getId();
                    $temp['order_id'] = (string)$sku_cls->getOrderId();
                    $temp['product_id'] = (string)$sku_cls->getProductId();
                    $temp['product_name'] = (string)$sku_cls->getProductName();
                    $temp['product_sku_id'] = (string)$sku_cls->getProductSkuId();
                    $temp['product_sku_attr'] = (string)$sku_cls->getProductSkuAttr();
                    $temp['individual_packing'] = (string)$sku_cls->getSellUnitString(); // 老版本
                    $temp['mass_packing'] = (string)$sku_cls->getSellUnitString(); // 老版本
                    $temp['sell_unit_string'] = (string)$sku_cls->getSellUnitString();
                    $temp['active_condition'] = (string)$sku_cls->getActiveCondition();
                    $temp['active_num'] = (string)$sku_cls->getActiveNum();
                    $temp['active_discount'] = (string)$sku_cls->getActiveDiscount();
                    $temp['cost'] = (string)$sku_cls->getCost();
                    $temp['price'] = (string)$sku_cls->getPrice();
                    $temp['amount'] = (string)$sku_cls->getAmount();
                    $temp['repertory_sum'] = (string)$sku_cls->getRepertorySum();
                    $temp['total'] = (string)$sku_cls->getTotal();
                    $temp['is_active'] = (string)$sku_cls->getActiveStatus();
                    $temp['img'] = $inco_url;
                    $orderBody[] = $temp;
                }
            }
        }

        return array('orderHeader' => $orderHeader, 'orderBody' => $orderBody, 'orderSettlement'=>$orderSettlement);
    }

    /*
     * 拼凑用户信息
     * @param  Cls\Order\Order  $order_cls
     */
    private function pieceUserInfo(\Cls\Order\Order $order_cls)
    {
        $userInfo = array();
        $user = $order_cls->getEnterpriseCustomerInfo();
        $region = $user->getRegion();

        $userInfo['id'] = (string)$user->getId();
        $userInfo['account'] = (string)$user->getAccount();
        $userInfo['pwd'] = (string)$user->getPassword();
        //$userInfo['name']               = $user->getName();
        //$userInfo['qq']                 = $user->getQQ();
        $userInfo['company'] = (string)$user->getCompany();
        $userInfo['contact'] = (string)$user->getContact();
        $userInfo['admin_id'] = (string)$user->getAdminId();
        //$userInfo['department']         = $user->getDepartment();
        $userInfo['customer_code'] = (string)$user->getCustomerCode();
        $userInfo['tel'] = (string)$user->getTelephone();
        $userInfo['channel_id'] = (string)$user->getChannelId();
        $userInfo['enterprise_id'] = (string)$user->getEnterpriseId();
        //$userInfo['enterprise_role_id'] = $user->getEnterpriseRoleId();
        $userInfo['warehouse_id'] = (string)$user->getWarehouseId();
        $userInfo['country'] = (string)$region->getCountryId();
        $userInfo['countryname'] = (string)$region->getCountryName();
        $userInfo['province'] = (string)$region->getProvinceId();
        $userInfo['provincename'] = (string)$region->getProvinceName();
        $userInfo['city'] = (string)$region->getCityId();
        $userInfo['cityname'] = (string)$region->getCityName();
        $userInfo['area'] = (string)$region->getAreaId();
        $userInfo['areaname'] = (string)$region->getAreaName();
        $userInfo['address'] = (string)$region->getAddress();
        //$userInfo['email']              = $user->getEmail();
        //$userInfo['type']               = (string)$user->getType();
        $userInfo['remark'] = (string)$user->getRemark();
        $userInfo['is_del'] = (string)$user->getDelStatus();
        //$userInfo['is_use']             = (string)$user->getUseStatus();
        $userInfo['insert_time'] = (string)$user->getCreateTime();
        $userInfo['update_time'] = (string)$user->getUpdateTime();

        return $userInfo;
    }

    /*
     * 拼凑在线支付
     * @param  Cls\Pay\Online  $online_cls
     */
    private function pieceOnline($online_list)
    {
        $online = array();
        $online_info = array();
        foreach ($online_list as $online_cls) {
            $online['id'] = $online_cls->getId();
            $online['code'] = $online_cls->getCode();
            $online['name'] = $online_cls->getPayTypeName();
            $online['icon'] = $online_cls->getIcon();
            $online['is_checked'] = $online_cls->getDefault();
            $online_info[] = $online;
        }
        return $online_info;
    }

    /*
     * 拼凑线下支付
     * @param  Cls\Pay\Offline  $offline_cls
     */
    private function pieceOffline($offline_list)
    {
        $offline = array();
        $offline_info = array();
        foreach ($offline_list as $offline_cls) {
            $offline['id'] = $offline_cls->getId();
            $offline['bank_name'] = $offline_cls->getBankName();
            $offline['bank_number'] = $offline_cls->getBankNumber();
            $offline['account'] = $offline_cls->getAccount();
            $offline['is_checked'] = $offline_cls->getDefault();
            $offline_info[] = $offline;
        }
        return $offline_info;
    }

    //创建solor订单
    private function createSolrOrderRow($tmpOrder)
    {
        if (empty($tmpOrder)) return false;
        $oH = $tmpOrder['orderHeader'];
        $oB = $tmpOrder['orderBody'];
        $u = $tmpOrder['userInfo'];
        $product_ids = self::getProducts($oB, 'id') ? self::getProducts($oB, 'id') : '';
        $product_names = self::getProducts($oB, 'product_names') ? self::getProducts($oB, 'product_names') : '';
        $channel_handler = new \Biz\ChannelHandler();
        $channel_cls = $channel_handler->getChannelById($oH['enterprise_channel_id']);
        $solr_order_cls = new \Cls\Order\SolrOrder();
        $solr_order_cls->setOrderId($oH['id']);
        $solr_order_cls->setOrderCode($oH['ordercode']);
        $solr_order_cls->setStatus($oH['status']);
        $solr_order_cls->setPayStatus($oH['pay_status']);
        $solr_order_cls->setDeliveryStatus($oH['delivery_status']);
        $solr_order_cls->setCustomerId($u['id']);
        $solr_order_cls->setCustomerAccount($u['company']);
        $solr_order_cls->setCustomerCode($u['customer_code']);
        $solr_order_cls->setEnterpriseId($oH['enterprise_id']);
        $solr_order_cls->setEnterpriseChannelId($oH['enterprise_channel_id']);
        $solr_order_cls->setEnterpriseChannelName($channel_cls->getName());
        $solr_order_cls->setProductIds($product_ids);
        $solr_order_cls->setProductNames($product_names);
        $solr_order_cls->setNeedPayPrice($oH['need_pay_price']);
        $solr_order_cls->setCreateTime(date('YmdHis', strtotime($oH['insert_time'])));

        $solr_order = new \Biz\Solr\OrderBiz();
        $res = $solr_order->insert($solr_order_cls);
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }

    private static function getProducts($items, $type = 'id')
    {
        if (empty($items)) return false;
        $items = json_decode(json_encode($items), true);
        $tmp = array();
        if ($type == 'id') {
            $vk = 'product_id';
        } else if ($type == 'product_names') {
            $vk = 'product_name';
        } else {
            $vk = 'product_id';
        }
        foreach ($items as $k => $v) {
            array_push($tmp, $v[$vk]);
        }
        if ($tmp) {
            return implode(',', $tmp);
        }
        return $tmp;
    }
}